//
//  AESUtil.m
//  Pthread
//
//  Created by Yanyan Jiang on 2025/3/6.
//  Copyright © 2025 Yanyan Jiang. All rights reserved.
//


#import "AESUtil.h"
#import <CommonCrypto/CommonCryptor.h>

@implementation AESUtil

#pragma mark - 密钥生成
+ (NSData *)generateAES256Key {
    NSMutableData *key = [NSMutableData dataWithLength:kCCKeySizeAES256];
    int result = SecRandomCopyBytes(kSecRandomDefault, kCCKeySizeAES256, key.mutableBytes);
    NSAssert(result == errSecSuccess, @"Failed to generate random AES key");
    return [key copy];
}

+ (NSData *)generateIV {
    NSMutableData *iv = [NSMutableData dataWithLength:kCCBlockSizeAES128];
    int result = SecRandomCopyBytes(kSecRandomDefault, kCCBlockSizeAES128, iv.mutableBytes);
    NSAssert(result == errSecSuccess, @"Failed to generate random IV");
    return [iv copy];
}

#pragma mark - 加密解密核心方法
+ (NSData *)aesEncryptData:(NSData *)data key:(NSData *)key iv:(NSData *)iv {
    // 参数校验
    if (key.length != kCCKeySizeAES256 || iv.length != kCCBlockSizeAES128) {
        NSLog(@"Invalid key/iv size");
        return nil;
    }
    
    // 准备加密参数
    size_t bufferSize = data.length + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    size_t numBytesEncrypted = 0;
    
    // 执行加密
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,               //操作类型：加密
                                          kCCAlgorithmAES,          //算法：AES
                                          kCCOptionPKCS7Padding,    //填充方式：PKCS7
                                          key.bytes,                //密钥字节
                                          kCCKeySizeAES256,         //密钥长度
                                          iv.bytes,                 //IV 字节
                                          data.bytes,               //输入数据字节
                                          data.length,              //输入数据长度
                                          buffer,                   //输出缓冲区
                                          bufferSize,               //输出缓冲区大小
                                          &numBytesEncrypted);      //加密后数据实际长度
    
    if (cryptStatus == kCCSuccess) {
        return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
    } else {
        free(buffer);
        NSLog(@"Encryption failed: %d", cryptStatus);
        return nil;
    }
}

+ (NSData *)aesDecryptData:(NSData *)data key:(NSData *)key iv:(NSData *)iv {
    // 参数校验
    if (key.length != kCCKeySizeAES256 || iv.length != kCCBlockSizeAES128) {
        NSLog(@"Invalid key/iv size");
        return nil;
    }
    
    // 准备解密参数
    size_t bufferSize = data.length + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    size_t numBytesDecrypted = 0;
    
    // 执行解密
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
                                          kCCAlgorithmAES,
                                          kCCOptionPKCS7Padding,
                                          key.bytes,
                                          kCCKeySizeAES256,
                                          iv.bytes,
                                          data.bytes,
                                          data.length,
                                          buffer,
                                          bufferSize,
                                          &numBytesDecrypted);
    
    if (cryptStatus == kCCSuccess) {
        return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
    } else {
        free(buffer);
        NSLog(@"Decryption failed: %d", cryptStatus);
        return nil;
    }
}

@end
